<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图片的懒加载实现方式1</title>
    <style>
        img {
            display: block;
        }
    </style>
</head>

<body>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <p>11111111111111111</p>
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">
    <img src="" data-src="./head.jpg" alt="">

    <script>
        // 获取所有图片标签
        let images = document.querySelectorAll('img')
        // 监听滚动事件（节流优化）
        window.addEventListener('scroll', throttle((e) => {
            // 遍历每一个图片标签
            images.forEach(item => {
                // 获取当前图片距离顶部的距离
                let itemTop = item.getBoundingClientRect().top
                // 如果小于当前窗口的高度，说明在窗口显示区域
                if (itemTop < window.innerHeight) {
                    let imageSrc = item.getAttribute('data-src')
                    // 给src属性赋值
                    item.setAttribute('src', imageSrc)
                    
                }
            })
            console.log('显示');
        }, 1000))

        // 节流优化函数
        function throttle(fn, t) {
            let timer, last;
            return function () {
                let args = arguments
                let now = +new Date()
                if (last && now - last < t) {
                    clearTimeout(timer)
                    timer = setTimeout(() => {
                        last = now
                        fn.apply(this, args)
                    }, t);
                } else {
                    last = now
                    fn.apply(this, args)
                }
            }
        }

    </script>
</body>

</html>